﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp2.Score;
using WindowsFormsApp2.Tools;
using WindowsFormsApp2.Util;
using WindowsFormsApp2.VTO;

namespace WindowsFormsApp2
{
    public partial class PdfForm : Form
    {
        public PdfForm()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        public List<String> m_images = new List<string>();

        PDFUtil pDFUtil = new PDFUtil();
        int current_index = 0;
        string current_file = String.Empty;

        RequestTools requestTools = new RequestTools();

        RegUtil regUtil = new RegUtil();

        const string last_user = "last_user";
        const string last_gx = "last_gx";


        private void button1_Click_1(object sender, EventArgs e)
        {
            if(openFileDialog1.ShowDialog()==DialogResult.OK)
            {
                m_images.Clear();


                var m_files = pDFUtil.getPdfImages(openFileDialog1.FileName, ImageFormat.Png);

                m_images.AddRange(m_files);

                if (m_files.Count > 0)
                {
                    current_file = m_files[0];
                    current_index = 0;

                    RenderInfo(current_file);
                }
            }
        }


        private void RenderInfo(string img_file)
        {
            var ret = requestTools.SendRequest(current_file);

            JObject json_boj = JObject.Parse(ret);


            //MessageBox.Show(json_boj.ToString());

            if (json_boj["code"].ToString() == "0") { 
                MessageBox.Show(json_boj["msg"].ToString());
                return;
            }

            listView1.Items.Clear();

            for (int ixxx = 1; ixxx < 21; ixxx++)
            {
                listView1.Items.Add(ixxx.ToString());
            }

            listView1.FullRowSelect = true;

            ReqResult req = JsonConvert.DeserializeObject<ReqResult>(json_boj.ToString());

            int h = req.data.h;

            int w = req.data.w;

            var img = Image.FromFile(img_file);

            Graphics g = Graphics.FromImage(img);

            Brush redBrush = new SolidBrush(Color.Red);
            Brush greenBrush = new SolidBrush(Color.Green);
            Pen redPen = new Pen(redBrush, 1);
            Pen greenPen = new Pen(greenBrush, 1);

            int iTop = findTop(req.data.find_points);
            int i = 0;
            int point_i = 0;
            List<List<VTO.Point>> point_array = req.data.point_array;
           

            foreach (var pt_a in req.data.point_array)
            {
                int array_size = pt_a.Count;
                Pen drawPen = array_size == 4 ? redPen : greenPen;
                Brush drawBrush = array_size == 4 ? redBrush : greenBrush;

                foreach (var ptx in pt_a)
                {
                    g.FillRectangle(drawBrush,
                        ptx.y,
                        ptx.x,
                        w,
                        h);
                }


            }

            int lv_index = 0;

            foreach (var score in req.data.score_array)
            {
                //textBox1.Text = textBox1.Text + score.ToString() + Environment.NewLine;
                listView1.Items[lv_index].SubItems.Add(score.ToString());
                //g.DrawString(score.ToString(),
                //    new Font("Arial", 10, FontStyle.Bold),
                //    redBrush,
                //    new System.Drawing.Point(2800, iTop));

                iTop += 52;

                lv_index++;
            }

            pictureBox1.Image = img;

            if (req.data.total_point_count == 80)
            {
                label1.Text = "完全识别！";
                label1.ForeColor = Color.Green;
            }
            else
            {
                label1.Text = "存在异常状况，请双击编辑！识别个数为：" + req.data.total_point_count;
                label1.ForeColor = Color.Red;
            }

        }

        private int findTop(List<VTO.Point> points)
        {
            int iRet = 10000;

            foreach (var pt in points)
            {
                if (pt.y < iRet)
                {
                    iRet = pt.y;
                }
            }

            return iRet;
        }

        private void PdfForm_Load(object sender, EventArgs e)
        {

        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            if(current_index<m_images.Count-1)
            {
                current_index++;
                current_file = m_images[current_index];

                RenderInfo(current_file);

                lbl_index.Text = $"{current_index+1}/{m_images.Count}张";

                //MessageBox.Show("加载完下一张！");
            }
            else
            {
                MessageBox.Show("已经完全完成！");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var user_name = tb_username.Text.Trim();

            var guangxi = cbb_shenfen.Text;

            if (user_name.Length == 0 || guangxi.Length == 0)
            {
                MessageBox.Show("姓名和关系为空,无法继续！");
                return;
            }

            foreach (ListViewItem item in listView1.Items)
            {
                if (item.SubItems.Count == 0)
                {
                    MessageBox.Show("当前存在空值，请编辑以后再保存！");
                    return;
                }
            }

            //var lines = textBox1.Lines;

            List<String> str_lines = new List<string>();

            foreach (ListViewItem item in listView1.Items)
            {
                str_lines.Add(item.SubItems[1].Text);
            }

            string total_line_score = String.Join(",", str_lines);

            string final_line = $"{user_name},{guangxi},{total_line_score}";

            string CSV_Name = AppUtil.GetAppDir() + @"Result\result.csv";

            File.AppendAllLines(CSV_Name, new string[] { final_line }, Encoding.Default);

            regUtil.WriteString(last_user, user_name);
            regUtil.WriteString(last_gx, cbb_shenfen.Text);

            MessageBox.Show("入库成功，请做好入库标记！");
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                var selItem = listView1.SelectedItems[0];

                new EditScore
                {
                    m_lv = selItem,
                    StartPosition = FormStartPosition.CenterScreen,
                    Left = listView1.Left
                }.ShowDialog();
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            string pdf_dir = AppUtil.GetAppDir() + @"pdf\";

            DirUtil.DelectDir(pdf_dir);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //2665,286 745,55
            //2665,400 727,55
            int name_left = 2660;
            int name_top = 232;

            int name_width = 760;
            int name_height = 310;


            string cur_png = m_images[current_index];

            var find_txts = IdentifyName(name_left, name_top, name_width, name_height, cur_png);

            if (find_txts.Count > 0) {
                tb_username.Text = find_txts[0];

                cbb_shenfen.Text = find_txts.Count > 1 ? find_txts[1] : "";
            }

            //cbb_shenfen.Text = IdentifyName(2650, 450, 655, 61, cur_png);
        }


        public List<String> IdentifyName(int left,int top, int width,int height,string file_name)
        {
            var temp_png = AppUtil.GetAppDir() + @"temp\" + Guid.NewGuid().ToString() + ".png";

            PngUtil.CaptureImage(file_name, left, top, temp_png, width, height);


            string request_result = requestTools.GetName(temp_png);

            JObject jObj = JObject.Parse(request_result);

            List<String> lines = new List<string>();

            if (jObj["code"].ToString() != "200")
            {

                return lines;
            }

            JToken name_array = jObj["data"]["raw_out"];

            StringBuilder sb = new StringBuilder();

            var hanzis = from s in name_array.Children() select s;

            

            foreach (var h in hanzis)
            {
                lines.Add(h[1].ToString());
            }

            return lines;
        }


    }
}
